package com.zhang.authoritycenter.security;

import com.alibaba.fastjson.JSON;
import com.zhang.infrastructure.model.KingHoodResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

   @Override
   public void commence(HttpServletRequest request,
                        HttpServletResponse response,
                        AuthenticationException authException) throws IOException {
      // 当用户尝试访问安全的REST资源而不提供任何凭据时，我们应该只发送401未经授权的响应，
      // 因为没有 “登录页面” 重定向到这里你可以放置任何你想要的消息
//      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

      log.error("上下文没有鉴权信息，说明jwt校验失败了，无效token，{}",authException.getMessage());
      response.setContentType("application/json;charset=utf-8");
      KingHoodResponseVO<Object> kingHoodResponseVO = KingHoodResponseVO.fail(HttpServletResponse.SC_UNAUTHORIZED, "重新登录");
      response.getWriter().println(JSON.toJSONString(kingHoodResponseVO));
      response.getWriter().flush();
   }
}
